package com.universalInterface.lims_interface.service.impl;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.universalInterface.common.exception.BusinessException;
import com.universalInterface.lims_interface.entity.LabInfo;
import com.universalInterface.lims_interface.entity.TestInfo;
import com.universalInterface.lims_interface.mapper.LabInfoMapper;
import com.universalInterface.lims_interface.mapper.TestInfoMapper;
import com.universalInterface.lims_interface.service.ITestInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 试验信息
 * </p>
 *
 * @author author
 * @since 2023-12-19
 */

@Service
public class TestInfoServiceImpl implements ITestInfoService {

    @Resource
    private TestInfoMapper testInfoMapper;
    @Autowired
    private LabInfoMapper labInfoMapper;
    public String realnum;

    @Override
    public TestInfo add(TestInfo testInfo) {
        QueryWrapper query = new QueryWrapper();
        // 查询实验室是否存在
        query.eq("lab_guid", testInfo.getLabGuid());
        LabInfo labInfo = labInfoMapper.selectOne(query);
        if (labInfo == null) {
            throw new BusinessException(500, "实验室数据不存在");
        }
        testInfo.setTestGuid(IdUtil.getSnowflakeNextId());
        testInfoMapper.insert(testInfo);
        return testInfo;
    }

    @Override
    public List<TestInfo> list(TestInfo testInfo) {
        QueryWrapper q = new QueryWrapper();
        if (testInfo.getLabGuid() != null) {
            q.eq("lab_guid", testInfo.getLabGuid());
        }
        if (q.isEmptyOfWhere()) {
            return null;
        }
        List<TestInfo> list = testInfoMapper.selectList(q);
        return list;
    }


    @Override
    public void clearTable(String labNum) {
        realnum = labNum + "TestData";
        testInfoMapper.clearTable(realnum);
    }

    @Override
    public TestInfo newestInfos(Long labGUID) {
        return testInfoMapper.newestInfos(labGUID);
    }

    @Override
    public Integer updateById(TestInfo testInfo) {
        // 不允许更新testGuid值
        if (testInfo.getTestGuid() != null) {
            throw new BusinessException(500, "不允许更新testGuid值");
        }
        // 查询实验室是否存在
        QueryWrapper q = new QueryWrapper();
        q.eq("lab_guid", testInfo.getLabGuid());
        LabInfo labInfo = labInfoMapper.selectOne(q);
        if (labInfo == null) {
            throw new BusinessException(500, "实验室数据不存在");
        }
        return testInfoMapper.updateById(testInfo);
    }

}
